<script setup lang="ts">
import type { CommonTreeProps, OpenParamProps, OptionProps } from '@/types';

import {
  type ComponentInternalInstance,
  computed,
  getCurrentInstance,
  ref,
} from 'vue';

import { Icon } from '@/components/core/icon';

import { ArrowRight } from '@element-plus/icons-vue';
import {
  ElBreadcrumb,
  ElBreadcrumbItem,
  ElDialog,
  ElMessage,
  ElMessageBox,
} from 'element-plus';

import { splitChar } from '@/utils';

defineOptions({
  name: 'MoveTo',
});
const emits = defineEmits(['confirm']);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const baseUrl = proxy?.$config.baseUrl;
const visible = ref(false);
const loading = ref(false);
const list = ref<CommonTreeProps[]>([]);
const currentPath = ref('');
const openParam = ref<OpenParamProps>();
const breadcrumb = computed(() => {
  if (currentPath.value === splitChar) return [];
  const paths = currentPath.value?.split(splitChar).filter(Boolean) || [];
  const result: OptionProps[] = [];
  let path = '';

  paths.forEach((item) => {
    if (item) {
      path += `${splitChar}${item}`;
      result.push({ name: item, path });
    }
  });

  return result;
});

const loadFolder = (path: string) => {
  currentPath.value = path;
  loading.value = true;
  try {
    const url = `${baseUrl}/folder/tree?path=${path}`;
    fetch(url, {
      method: 'GET',
    })
      .then((response) => response.json())
      .then((res) => {
        const { code, data, msg } = res;
        if (code === 200 && data) {
          data.map((m: CommonTreeProps) => {
            m.parentPath = path;
            return m;
          });
          list.value = data as CommonTreeProps[];
        } else {
          ElMessage.error(msg || '获取文件夹目录失败');
        }
      });
  } catch (error) {
    console.log(error);
    ElMessage.error('请求发生了错误，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 新建文件夹
const onNewFolder = () => {
  if (!currentPath.value) {
    ElMessage.warning('当前路径无法新建文件夹，请重试');
    return;
  }
  ElMessageBox.prompt('请输入文件夹名称', '新建文件夹', {
    buttonSize: 'small',
    cancelButtonText: '取消',
    confirmButtonText: '确定',
    customClass: 'wos-common-confirm',
    draggable: true,
    inputErrorMessage: '无效的名称，请重新输入',
    inputPattern: /^[^"%*/:<>?\\|]+$/,
    inputPlaceholder: '请输入新的文件或文件夹名称',
    inputValue: '新建文件夹',
  })
    .then(({ value }) => {
      loading.value = true;
      try {
        const postData = { name: value, path: currentPath.value };
        const url = `${baseUrl}/folder/newFolder`;
        fetch(url, {
          body: JSON.stringify(postData),
          headers: {
            'Content-Type': 'application/json;charset=utf-8',
          },
          method: 'POST',
        })
          .then((response) => response.json())
          .then((res) => {
            const { code, msg } = res;
            if (code === 200) {
              loadFolder(currentPath.value);
              ElMessage.success({
                message: msg || '新建文件夹成功',
                type: 'success',
              });
            } else {
              ElMessage.error(msg || '获取文件夹目录失败');
            }
          });
      } catch (error) {
        console.log(error);
        ElMessage.error('请求发生了错误，请稍后重试');
      } finally {
        loading.value = false;
      }
    })
    .catch(() => {
      console.log('取消');
    });
};

const onConfirm = () => {
  // 设置回调并执行
  if (
    openParam.value?.callback &&
    typeof openParam.value?.callback === 'function'
  ) {
    openParam.value?.callback({ path: currentPath.value });
  } else {
    emits('confirm', {
      path: currentPath.value,
    });
  }
  visible.value = false;
};

const onItemDbClick = (item: CommonTreeProps) => {
  const { path } = item;
  currentPath.value = path || splitChar;
  loadFolder(path);
};
// 跳转到指定目录
const onGoto = (path: string) => {
  if (path) {
    loadFolder(path);
    currentPath.value = path;
  }
};
const open = (data?: OpenParamProps) => {
  openParam.value = Object.assign({}, data);
  visible.value = true;
  const path = data?.path || splitChar;
  loadFolder(path);
};
defineExpose({
  open,
});
</script>
<template>
  <ElDialog
    v-model="visible"
    :align-center="true"
    :center="true"
    :close-on-click-modal="false"
    :draggable="true"
    modal-class="wos-folder-common-dialog"
    width="640"
  >
    <template #header>
      <div class="dialog-header">
        {{ openParam?.title || '打开要移动的目标文件夹' }}
      </div>
    </template>
    <div class="dialog-body">
      <div class="dialog-body--breadcrumb">
        <ElBreadcrumb :separator-icon="ArrowRight">
          <ElBreadcrumbItem @click="onGoto(splitChar)">根目录</ElBreadcrumbItem>
          <ElBreadcrumbItem
            v-for="(item, index) in breadcrumb"
            :key="index"
            :title="item.name"
            @click="onGoto(item.path)"
          >
            {{ item.name }}
          </ElBreadcrumbItem>
        </ElBreadcrumb>
      </div>
      <div class="dialog-body--grid small">
        <div
          v-for="(item, index) in list"
          :key="index"
          class="grid-item"
          @dblclick="onItemDbClick(item)"
        >
          <Icon icon="mdi:folder" />
          <div :title="item.label" class="name">
            {{ item.label }}
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer flex items-center justify-between">
        <ElButton size="small" @click="onNewFolder">新建文件夹</ElButton>
        <ElButton size="small" type="primary" @click="onConfirm">
          确定
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<style lang="scss">
@import url('./index.scss');
</style>
